//
//  TabView.swift
//  Jock
//
//  Created by HD on 15/3/25.
//  Copyright (c) 2015年 Haidy. All rights reserved.
//

import UIKit

protocol TabViewDelegate {
    
    func select(item: TabItem, index: Int)
}

class TabView: UIToolbar {
    
    var tabViewDelegate: TabViewDelegate?
    
    private var tabItems: [TabItem]?
    
    // 设置tabItems
    func setTabItems(items: [TabItem]) {
        let itemWidth = (self.frame.width - 38 - CGFloat((items.count - 1) * 8)) / CGFloat(items.count)
        var barItems = [UIBarButtonItem]()
        var currentX: CGFloat = 0
        var index = 0
        for item in items {
            item.frame = CGRectMake(0, 0, itemWidth, self.frame.height)
            var tap = UITapGestureRecognizer(target: self, action: "selection:")
            item.tag = index
            item.addGestureRecognizer(tap)
            barItems.append(UIBarButtonItem(customView: item))
            currentX += itemWidth
            currentX += 8
            index++
        }
        self.setItems(barItems, animated: false)
        self.tabItems = items
    }
    
    func selection(tap: UITapGestureRecognizer) {
        let item = tap.view as! TabItem
        item.select = true
        
        if tabViewDelegate != nil {
            for tabItem in tabItems! {
                if item.tag != tabItem.tag {
                    tabItem.select = false
                }
            }
            tabViewDelegate?.select(item, index: item.tag)
        }
    }
}